import requests
import json

from core import tools
from core import settings

def get_login_url():
    return f"https://login.live.com/oauth20_authorize.srf?client_id=00000000402b5328&response_type=code&scope=service%3A%3Auser.auth.xboxlive.com%3A%3AMBI_SSL&redirect_uri=https%3A%2F%2Flogin.live.com%2Foauth20_desktop.srf"

def get_url_code(url):
    return url.split("?")[1].split("&")[0].split("=")[1].split(".")[2] # 不会写正则

def login(url):
    try:
        code=get_url_code(url)
    except:
        return "url不合法"
    oaurl=f"https://login.live.com/oauth20_desktop.srf"
    oatoken=f"https://login.live.com/oauth20_token.srf"
    xblurl=f"https://user.auth.xboxlive.com/user/authenticate"
    oadata={
        "client_id":"00000000402b5328",
        "code":code,
        "grant_type":"authorization_code",
        "redirect_uri":f"https://login.live.com/oauth20_desktop.srf",
        "scope":f"service::user.auth.xboxlive.com::MBI_SSL"
    }
    try:
        post_req=requests.post(oatoken,data=oadata)
    except:
        return "网络错误[OAUTH]"
    try:
        req_content=json.loads(str(post_req.text))
        acc_token=req_content["access_token"]
        ref_token=req_content["refresh_token"]
    except:
        return "获取token错误[通常是网络或过期链接导致]"
    xbl_json={
        "Properties": {
            "AuthMethod": "RPS",
            "SiteName": "user.auth.xboxlive.com",
            "RpsTicket": acc_token
        },
        "RelyingParty": "http://auth.xboxlive.com",
        "TokenType": "JWT"
    }
    try:
        post_req_xbl=requests.post(xblurl,json=json.dumps(xbl_json))
    except:
        return "网络错误[XBL]"
    try:
        req_content_xbl=(str(post_req_xbl.text))
    except:
        return "获取xbl_token错误[通常是没买正版或网络导致]"
    print(acc_token)
    print(req_content_xbl,post_req_xbl.status_code)
    return None

